package com.bxl.chooser.util;

import com.bxl.netty.rpc.common.pool.ThreadPoolUtil;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <>
 *
 * @author baixl
 * @date 2021/3/8
 */
public class ThreadUtil {
    private static ScheduledThreadPoolExecutor scheduled;
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 4, 3, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(10),
            new MyThreadFactory("executor"), new ThreadPoolExecutor.CallerRunsPolicy());
    static {
        scheduled = new ScheduledThreadPoolExecutor(2,
                new MyThreadFactory("scheduleAtFixedRate"), new ThreadPoolExecutor.CallerRunsPolicy());
        scheduled.setRemoveOnCancelPolicy(true);
    }

    public static void submit(Runnable r) {
        executor.submit(r);
    }
    
    static class MyThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        MyThreadFactory(String prefix) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = prefix + "-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }


    /**
     * 延时定时执行
     *
     * @param r
     * @param initialDelay
     * @param period
     * @param unit
     * @return
     */
    public static ScheduledFuture scheduleWithFixedDelay(Runnable r, long initialDelay,
                                                      long period,
                                                      TimeUnit unit) {
        return scheduled.scheduleWithFixedDelay(r, initialDelay, period, unit);
    }

}
